package net.miranti.opmov.client;

import net.miranti.client.Callback;
import net.miranti.client.events.Handler;
import net.miranti.opmov.client.events.AirportsLoadedEvent;
import net.miranti.opmov.client.events.OpMovLoadedEvent;
import net.miranti.opmov.events.SetupEvent;
import net.miranti.opmov.events.StartupEvent;

import com.google.gwt.event.shared.HandlerManager;
import com.google.inject.Inject;

public class OpMovPresenter {
	final HandlerManager eventBus;
	final BtdServiceAsync service;

	private String airport;
	private Integer segment;
	private Integer variable;
	private Integer periodicity;

	@Inject
	public OpMovPresenter(final HandlerManager eventBus,
			final BtdServiceAsync service) {
		this.eventBus = eventBus;
		this.service = service;

		eventBus.addHandler(StartupEvent.TYPE, new Handler<StartupEvent>() {
			@Override
			public void onEvent(StartupEvent e) {
				loadAirports();
			}
		});
		eventBus.addHandler(SetupEvent.TYPE, new Handler<SetupEvent>() {
			@Override
			public void onEvent(SetupEvent e) {
				airport = e.airport;
				segment = e.segment;
				variable = e.variable;
				periodicity = e.periodicity;

				loadAirports();

				service.search(airport, new Callback<OpMovBean[]>(eventBus) {
					@Override
					public void onSuccess(OpMovBean[] result) {
						eventBus.fireEvent(new OpMovLoadedEvent(result));
					}
				});
			}
		});
	}

	private void loadAirports() {
		service.getAirports(new Callback<Airport[]>(eventBus) {
			@Override
			public void onSuccess(Airport[] result) {
				eventBus.fireEvent(new AirportsLoadedEvent(result, airport));
			}
		});
	}
}
